package com.atguigu.gmall.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.app.BaseAppV2;
import com.atguigu.gmall.bean.OrderWide;
import com.atguigu.gmall.bean.PaymentWide;
import com.atguigu.gmall.bean.ProductStats;
import com.atguigu.gmall.common.Constant;
import com.atguigu.gmall.function.DimAsyncFunction;
import com.atguigu.gmall.util.DimUtil;
import com.atguigu.gmall.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.atguigu.gmall.common.Constant.*;
import static com.atguigu.gmall.util.AtguiguCommonUtil.toTs;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/6 9:02
 */
public class DwsProductStatsApp extends BaseAppV2 {
    public static void main(String[] args) {
        new DwsProductStatsApp().init(
            4002,
            1,
            "DwsProductStatsApp",
            "DwsProductStatsApp",
            TOPIC_DWD_PAGE, Constant.TOPIC_DWD_DISPLAY,
            Constant.TOPIC_DWD_FAVOR_INFO, Constant.TOPIC_DWD_CART_INFO,
            Constant.TOPIC_DWM_ORDER_WIDE, Constant.TOPIC_DWM_PAYMENT_WIDE,
            Constant.TOPIC_DWD_ORDER_REFUND_INFO, Constant.TOPIC_DWD_COMMENT_INFO);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env, Map<String, DataStreamSource<String>> streams) {
        // 1. 把8个流union在一起
        DataStream<ProductStats> productStatsStream = unionStreams(streams);
        // 2. 开窗聚合
        SingleOutputStreamOperator<ProductStats> aggregatedStream = agg(productStatsStream);
        // 3. 补齐维度
        SingleOutputStreamOperator<ProductStats> psStreamWithDim = joinDim(aggregatedStream);
        // 4. 写入到ClickHouse中
        writeToClickHouse(psStreamWithDim);
        
        // 5. 写入到Kafka中 为了给产品关键词准备数据
        writeToKafka(psStreamWithDim);
        
    }
    
    private void writeToKafka(SingleOutputStreamOperator<ProductStats> stream) {
        stream
            .map(JSON::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWS_PRODUCT_STATS));
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<ProductStats> psStreamWithDim) {
        psStreamWithDim.addSink(
            FlinkSinkUtil.getClickHouseSink(
                CLICKHOUSE_DB, TABLE_PRODUCT_STATS, ProductStats.class
            ));
    }
    
    private SingleOutputStreamOperator<ProductStats> joinDim(SingleOutputStreamOperator<ProductStats> aggregatedStream) {
        return AsyncDataStream.unorderedWait(
            aggregatedStream,
            new DimAsyncFunction<ProductStats>() {
                @Override
                public void addDim(Connection phoenixConn,
                                   Jedis client,
                                   ProductStats ps,
                                   ResultFuture<ProductStats> resultFuture) throws Exception {
                    JSONObject skuInfo = DimUtil.readDim(phoenixConn, client, DIM_SKU_INFO, ps.getSku_id().toString());
                    ps.setSku_name(skuInfo.getString("SKU_NAME"));
                    ps.setSku_price(skuInfo.getBigDecimal("PRICE"));
                    
                    ps.setSpu_id(skuInfo.getLong("SPU_ID"));
                    ps.setTm_id(skuInfo.getLong("TM_ID"));
                    ps.setCategory3_id(skuInfo.getLong("CATEGORY3_ID"));
                    
                    // 4. spu
                    JSONObject spuInfo = DimUtil.readDim(phoenixConn, client, DIM_SPU_INFO, ps.getSpu_id().toString());
                    ps.setSpu_name(spuInfo.getString("SPU_NAME"));
                    // 5. tm
                    JSONObject tmInfo = DimUtil.readDim(phoenixConn, client, DIM_BASE_TRADEMARK, ps.getTm_id().toString());
                    ps.setTm_name(tmInfo.getString("TM_NAME"));
                    
                    // 5. c3
                    JSONObject c3Info = DimUtil.readDim(phoenixConn, client, DIM_BASE_CATEGORY3, ps.getCategory3_id().toString());
                    ps.setCategory3_name(c3Info.getString("NAME"));
                    
                    resultFuture.complete(Collections.singletonList(ps));
                    
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<ProductStats> agg(DataStream<ProductStats> productStatsStream) {
        return productStatsStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<ProductStats>forBoundedOutOfOrderness(Duration.ofSeconds(20))
                    .withTimestampAssigner((ps, ts) -> ps.getTs())
            )
            .keyBy(ProductStats::getSku_id)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<ProductStats>() {
                    @Override
                    public ProductStats reduce(ProductStats ps1, ProductStats ps2) throws Exception {
                        ps1.setClick_ct(ps1.getClick_ct() + ps2.getClick_ct());
                        ps1.setDisplay_ct(ps1.getDisplay_ct() + ps2.getDisplay_ct());
                        ps1.setFavor_ct(ps1.getFavor_ct() + ps2.getFavor_ct());
                        ps1.setCart_ct(ps1.getCart_ct() + ps2.getCart_ct());
                        ps1.setComment_ct(ps1.getComment_ct() + ps2.getComment_ct());
                        ps1.setGood_comment_ct(ps1.getGood_comment_ct() + ps2.getGood_comment_ct());
                        
                        ps1.setOrder_sku_num(ps1.getOrder_sku_num() + ps2.getOrder_sku_num());
                        ps1.setOrder_amount(ps1.getOrder_amount().add(ps2.getOrder_amount()));
                        
                        ps1.setPayment_amount(ps1.getPayment_amount().add(ps2.getPayment_amount()));
                        ps1.setRefund_amount(ps1.getRefund_amount().add(ps2.getRefund_amount()));
                        
                        ps1.getOrderIdSet().addAll(ps2.getOrderIdSet());
                        ps1.getPaidOrderIdSet().addAll(ps2.getPaidOrderIdSet());
                        ps1.getRefundOrderIdSet().addAll(ps2.getRefundOrderIdSet());
                        
                        return ps1;
                    }
                },
                new ProcessWindowFunction<ProductStats, ProductStats, Long, TimeWindow>() {
                    
                    private SimpleDateFormat sdf;
                    
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                    
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<ProductStats> elements,
                                        Collector<ProductStats> out) throws Exception {
                        TimeWindow w = ctx.window();
                        
                        ProductStats ps = elements.iterator().next();
                        ps.setStt(sdf.format(w.getStart()));
                        ps.setEdt(sdf.format(w.getEnd()));
                        
                        ps.setOrder_ct((long) ps.getOrderIdSet().size());
                        ps.setPaid_order_ct((long) ps.getPaidOrderIdSet().size());
                        ps.setRefund_order_ct((long) ps.getRefundOrderIdSet().size());
                        
                        out.collect(ps);
                    }
                }
            );
    }
    
    private DataStream<ProductStats> unionStreams(Map<String, DataStreamSource<String>> streams) {
        
        // 1. 点击
        SingleOutputStreamOperator<ProductStats> clickStatsStream = streams
            .get(TOPIC_DWD_PAGE)
            .flatMap(new FlatMapFunction<String, ProductStats>() {
                @Override
                public void flatMap(String value,
                                    Collector<ProductStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    JSONObject page = obj.getJSONObject("page");
                    String pageId = page.getString("page_id");
                    
                    String itemType = page.getString("item_type");
                    
                    if ("good_detail".equals(pageId)
                        && page.get("item") != null
                        && "sku_id".equals(itemType)) {
                        
                        Long item = page.getLong("item");
                        ProductStats ps = new ProductStats();
                        ps.setSku_id(item);
                        ps.setClick_ct(1L);
                        ps.setTs(obj.getLong("ts"));
                        out.collect(ps);
                    }
                }
            });
        
        // 2. 曝光
        SingleOutputStreamOperator<ProductStats> displayStatsStream = streams
            .get(TOPIC_DWD_DISPLAY)
            .map(s -> {
                JSONObject obj = JSON.parseObject(s);
                Long skuId = obj.getLong("item");
                Long ts = obj.getLong("ts");
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(skuId);
                ps.setTs(ts);
                
                ps.setDisplay_ct(1L);
                return ps;
            });
        
        // 3.收藏
        
        SingleOutputStreamOperator<ProductStats> favorStatsStream = streams
            .get(TOPIC_DWD_FAVOR_INFO)
            .map(s -> {
                JSONObject favor = JSON.parseObject(s);
                ProductStats ps = new ProductStats();
                ps.setSku_id(favor.getLong("sku_id"));
                ps.setFavor_ct(1L);
                ps.setTs(toTs(favor.getString("create_time")));
                
                return ps;
            });
        
        // 4. cart
        
        SingleOutputStreamOperator<ProductStats> cartStatsStream = streams
            .get(TOPIC_DWD_CART_INFO)
            .map(s -> {
                JSONObject cart = JSON.parseObject(s);
                ProductStats ps = new ProductStats();
                ps.setSku_id(cart.getLong("sku_id"));
                ps.setCart_ct(1L);
                ps.setTs(toTs(cart.getString("create_time")));
                
                return ps;
            });
        
        // 5. order
        SingleOutputStreamOperator<ProductStats> orderWideStatsStream = streams
            .get(TOPIC_DWM_ORDER_WIDE)
            .map(s -> {
                OrderWide orderWide = JSON.parseObject(s, OrderWide.class);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(orderWide.getSku_id());
                ps.getOrderIdSet().add(orderWide.getOrder_id());
                ps.setTs(toTs(orderWide.getCreate_time()));
                
                ps.setOrder_amount(orderWide.getSplit_total_amount());
                ps.setOrder_sku_num(orderWide.getSku_num());
                
                return ps;
                
            });
        
        // 5. 支付
        SingleOutputStreamOperator<ProductStats> paymentWideStatsStream = streams
            .get(TOPIC_DWM_PAYMENT_WIDE)
            .map(s -> {
                PaymentWide paymentWide = JSON.parseObject(s, PaymentWide.class);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(paymentWide.getSku_id());
                ps.setTs(toTs(paymentWide.getPayment_create_time()));
                
                ps.getPaidOrderIdSet().add(paymentWide.getOrder_id());
                ps.setPayment_amount(paymentWide.getSplit_total_amount());
                return ps;
                
            });
        
        // 6. 退款
        SingleOutputStreamOperator<ProductStats> refundStatsStream = streams
            .get(TOPIC_DWD_ORDER_REFUND_INFO)
            .map(s -> {
                JSONObject refund = JSON.parseObject(s);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(refund.getLong("sku_id"));
                ps.setRefund_amount(refund.getBigDecimal("refund_amount"));
                ps.getRefundOrderIdSet().add(refund.getLong("order_id"));
                ps.setTs(toTs(refund.getString("create_time")));
                return ps;
            });
        
        // 7. 评价
        SingleOutputStreamOperator<ProductStats> commentStatsStream = streams
            .get(TOPIC_DWD_COMMENT_INFO)
            .map(s -> {
                JSONObject comment = JSON.parseObject(s);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(comment.getLong("sku_id"));
                
                ps.setTs(toTs(comment.getString("create_time")));
                ps.setComment_ct(1L);
                
                String appraise = comment.getString("appraise");
                
                if (FOUR_STAR_COMMENT.equals(appraise) || FIVE_STAR_COMMENT.equals(appraise)) {
                    ps.setGood_comment_ct(1L);
                    
                }
                
                return ps;
            });
        
        return clickStatsStream.union(
            displayStatsStream,
            cartStatsStream,
            favorStatsStream,
            orderWideStatsStream,
            paymentWideStatsStream,
            commentStatsStream,
            refundStatsStream
        );
        
    }
}
